package org.rest.client;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URI;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.UriBuilder;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.ClientConfig;
import com.sun.jersey.api.client.config.DefaultClientConfig;
/**
 * Servlet implementation class Rest_Client
 */
@WebServlet("/Rest_Client")
public class Rest_Client extends HttpServlet {
	private static final long serialVersionUID = 1L;
    
	
	
	private static final String HOME_IP = "192.168.1.4";//using itt
	private static final String WORK_IP = "192.168.1.26";
	private static final String UNI_IP = "77.80.11.2";
	private static final String MUCHE_IP = "192.168.0.17";
	private static final String JANA_IP = "192.168.0.10";
	
	
	private static String USING_IP = WORK_IP;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Rest_Client() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		StringBuffer url_buffer  = request.getRequestURL();
		
		//String url = url_buffer.toString().replace("http://localhost:8080/RestClient/rest/", "");
		String url = url_buffer.toString().replace("http://"+USING_IP+":8080/RestClient/rest/", "");
	
		PrintWriter wr = response.getWriter();
		
		ClientConfig config = new DefaultClientConfig();
	    Client client = Client.create(config);
	    WebResource service = client.resource(getBaseURI());
	    // Fluent interfaces
	 //   wr.print(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(ClientResponse.class).toString());
	
	    // Get plain text
	    //System.out.println(service.path("rest").path("hello").accept(MediaType.TEXT_PLAIN).get(String.class));
	   // System.out.println("");
	    // Get XML
	    JSONObject inputJsonObj = new JSONObject();
	    
	    
	    if (url.startsWith("buyitem")) {
	    	
	    	String[] parts = url.split("-");
	    	try {
	 			inputJsonObj.put("name", parts[0]);
	 			inputJsonObj.put("category", parts[1]);
	 			
	 		} catch (JSONException e) {
	 			// TODO Auto-generated catch block
	 			e.printStackTrace();
	 		}
	    	
	    	inputJsonObj = ((service.path("rest").path(url).accept(MediaType.APPLICATION_JSON).entity(inputJsonObj).put(JSONObject.class)));
	    
	    } else if (url.startsWith("supplier")) { 
	    	System.out.println("supplier");
	    	String url_part = url.replace("supplier/", "");
	    	String[] parts = url.split("/");
	    	System.out.println("part 2"+parts[2]);
	    	
	    	if(parts[1].matches("[0-9]+")) {
	    		ObjectMapper mapper = new ObjectMapper();
	    	    
	    		Object json = null;
		    	String result = "";
		    	String indented = "" ;
		    	System.out.println("blub");
		   
	    		inputJsonObj = ((service.path("rest").path(url).accept(MediaType.APPLICATION_JSON).get(JSONObject.class)));
	    		result = inputJsonObj.toString();//restTemplate.getForObject(url.toString(), String.class);
		    	
	    		json = mapper.readValue(result, Object.class);
	    		indented = mapper.defaultPrettyPrintingWriter().writeValueAsString(json);
	    		wr.print(indented);
		    	System.out.println(indented);

	    		
	    	} else { 
	    		
	    	
	    		try {
	    			inputJsonObj.put("name", parts[2]);
	    			inputJsonObj.put("category", parts[3]);
	 			
	    		} catch (JSONException e) {
	 			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		}
	    	
	    		inputJsonObj = ((service.path("rest").path(url).accept(MediaType.APPLICATION_JSON).entity(inputJsonObj).put(JSONObject.class)));
	    	
	    		wr.print(inputJsonObj.toString());
	    	}
	    
	    }  else if (url.startsWith("item")) { 
	    	
	    	System.out.println("item");
	    	
	    	String url_part = url.replace("item/", "");
	    	
	    	ObjectMapper mapper = new ObjectMapper();
	    	Object json = null;
	    	String result = "";
	    	String indented = "" ;
	    	
	    	if (url_part.startsWith("buy")) {
	    		System.out.println("buy item");
	    		
	    		String[] parts = url.split("/");
		    	try {
		 			inputJsonObj.put("itemid", parts[2]);
		 			inputJsonObj.put("amount", parts[3]);
		 			inputJsonObj.put("companyid", parts[4]);
		 		} catch (JSONException e) {
		 			// TODO Auto-generated catch block
		 			e.printStackTrace();
		 		}
	    		
	    		inputJsonObj = ((service.path("rest").path(url).accept(MediaType.APPLICATION_JSON).entity(inputJsonObj).put(JSONObject.class)));
	    		
	    		result = inputJsonObj.toString();//restTemplate.getForObject(url.toString(), String.class);
		    	
	    		json = mapper.readValue(result, Object.class);
	    	
	    		indented = mapper.defaultPrettyPrintingWriter().writeValueAsString(json);
	    		
	    	} else {
	    		
	    		inputJsonObj = ((service.path("rest").path(url).accept(MediaType.APPLICATION_JSON).get(JSONObject.class)));
	    		    	
	    		result = inputJsonObj.toString();//restTemplate.getForObject(url.toString(), String.class);
	    	
	    		json = mapper.readValue(result, Object.class);
	    	
	    		indented = mapper.defaultPrettyPrintingWriter().writeValueAsString(json);
	    	
	    	}
	    
	    	wr.print(indented);
	    	System.out.println(indented);
	    
	    }	else if (url.startsWith("jurxpert")) { 
	    	
	    	if (url.startsWith("jurxpert/person/search")) {
	    		String search_parameter=request.getParameter("search_parameter");
	    		System.out.println(search_parameter);
	    		try {
					inputJsonObj.put("search_parameter",search_parameter);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	    	}
	    	else if (url.startsWith("jurxpert/person/details")) {
	    		String personnr =request.getParameter("personnr");
	    		try {
	    			inputJsonObj.put("personnr",personnr);
	    			
	    		} catch (JSONException e) {
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		}
	    	}
	    	else if (url.startsWith("jurxpert/akte/search")) {
	    		String search_parameter =request.getParameter("search_parameter");
	    		String search_type =request.getParameter("search_type");
	    		try {
	    			inputJsonObj.put("search_parameter",search_parameter);
	    			inputJsonObj.put("search_type",search_type);
	    		} catch (JSONException e) {
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		}
	    	}
	    	else {
	    		String username = request.getParameter("username");
	    		String password = request.getParameter("password");
	    		System.out.println(username);
	    		System.out.println(password);
	    		
	    		try {
	    			inputJsonObj.put("benutzername",username);
	    			inputJsonObj.put("password", password);
	    		} catch (JSONException e) {
	    			// TODO Auto-generated catch block
	    			e.printStackTrace();
	    		}
	    	}
	    	
	    	inputJsonObj = ((service.path("rest").path(url).accept(MediaType.APPLICATION_JSON).entity(inputJsonObj).post(JSONObject.class)));
	    	
	    	wr.print(inputJsonObj.toString());
	    	
	    }  else {
	    
	    	System.out.println("before blub");
	   
	  //  wr.print((service.path("rest").path("hello/1").accept(MediaType.APPLICATION_JSON).entity(inputJsonObj).put(JSONObject.class)));
	    
	    	inputJsonObj = ((service.path("rest").path(url).accept(MediaType.APPLICATION_JSON).entity(inputJsonObj).put(JSONObject.class)));
	    
	    	wr.print(inputJsonObj);
	    }
}
	    
	    // The HTML
	   // System.out.println(service.path("rest").path("hello/1").accept(MediaType.TEXT_HTML).put(String.class));
	   // System.out.println("");

	  private static URI getBaseURI() {
	    //return UriBuilder.fromUri("http://localhost:8080/Test_WebApp_1").build();
		  return UriBuilder.fromUri("http://"+USING_IP+":8080/Test_WebApp_1").build();
	  }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		System.out.println("im POST");
	}

}
